#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

char s[15];
string goal = "123456789";

struct node{  
    int f, step;  
    string now; 
	bool operator < (const node &x) const {  
        return f > x.f;        
    }  
};

priority_queue <node> q;
map <string, bool>mp;
map <string, int> dis;

int r_x[4]={0,0,1,1};
int r_y[4]={0,1,0,1};

void srotate(string sours,int x,int y){
    char c=sours[x*3+y];
    sours[x*3+y]=sours[x*3+y+1];
    sours[x*3+y+1]=sours[(x+1)*3+y+1];
    sours[(x+1)*3+y+1]=sours[(x+1)*3+y];
    sours[(x+1)*3+y]=c;
	return ;
}

void nrotate(string sours,int x,int y){
    char c=sours[x*3+y];
	sours[x*3+y] = sours[(x+1)*3+y+1];
    sours[(x+1)*3+y+1]=sours[(x+1)*3+y];
    sours[(x+1)*3+y]=sours[x*3+y+1];
    sours[x*3+y+1]=c;
	return;
}
int h(string cur){
	int res = 0;
	for (int i = 0; i < 9; i ++ ) 
        if (goal[i] != cur[i] && goal[i] != 0) res++;
	return res;
} 
void A_STAR(){
	while (!q.empty())
	{
		node t = q.top(); q.pop();
		string cur = t.now;
		if (cur == "123456789") {
			printf("%d\n", t.step);
		}
		for (int i = 0; i < 4; i++)
		{
			srotate(cur,r_x[i],r_y[i]);
			if (mp[cur] == 0 || (mp[cur] == 1 && (t.step + 1) < dis[cur])) {
				dis[cur] = t.step + 1;
				q.push((node){h(cur) + t.step + 1, t.step + 1, cur}); 
				mp[cur] = 1;
			}
			nrotate(cur,r_x[i],r_y[i]);
		}
		
	}
}

int main() {
	char temp;
	int i;
	while (scanf("%c",&temp)!=EOF)
	{
		for ( i = 0; i < 9; scanf("%c",&temp)) {
			if (isdigit(temp)) s[i++]=temp;
			if(i==9) break;
		}
		i =h(s);
		if (i==0) {puts("0");continue;}
		while(q.size()) q.pop();
		q.push((node){i, 0, s});
		mp[s] = 1;
		dis[s] = 0;
		A_STAR();
	}

	return 0;
}